import './ChatInputPanel.css'
import { memo, useState, useRef, useEffect } from 'react';
import useStore from '@/store';

const ChatInputPanel = memo(({ onEnter, disabled, focus }) => {
    // console.log('CharAreaInput');
    const textareaRef = useRef(null);
    const [promptValue, setPromptValue] = useState("");

    useEffect(() => {
        // 在组件挂载后获取焦点
        if (focus && textareaRef.current) {
            textareaRef.current.focus();
        }
    }, [focus,]);

    const handleKeyDown = (event) => {
        if (event.key === 'Enter') {
            if (event.shiftKey) {
                // Shift + Enter: 插入换行符
                return; // 允许换行
            } else {
                // Enter: 触发函数
                event.preventDefault(); // 阻止默认行为
                handleSubmit();
            }
        }
    };

    const handleSubmit = async () => {
        if (disabled) {
            return;
        }
        // 这里可以处理提交逻辑
        try {
            // console.log('Submitted:', promptValue);
            onEnter(promptValue, setPromptValue)
        } catch (error) {

        }
    };

    useEffect(() => {
        if (textareaRef.current) {
            if (textareaRef.current.scrollHeight > 144 && textareaRef.current.style.height === 144) return; // 限制最大高度(不可超过的高度)

            textareaRef.current.style.height = 'auto'; // 重置高度为内容物高度

            const scrollHeight = textareaRef.current.scrollHeight;

            if (scrollHeight < 0) return; // 防止空内容导致 textarea height 变为 0
            if (scrollHeight > 144) {
                textareaRef.current.style.height = '144px'; // 如果通过粘贴等手段突然超过144px

            } else {
                textareaRef.current.style.height = `${scrollHeight}px`; // 然后设置高度为 scrollHeight
            }

        }
    }, [promptValue]);

    return (
        // chat-input-panel
        <div className="chat-input-panel">
            <div className="chat-input-area">
                <textarea
                    className="chat-input-textarea"
                    ref={textareaRef}
                    value={promptValue}
                    onChange={(e) => setPromptValue(e.target.value)}
                    onKeyDown={handleKeyDown}
                    placeholder="Ask anything"
                    rows={1}
                    disabled={disabled}/>
                <div className="chat-input-send-button" style={{ cursor: disabled ? 'none' : '' }} onClick={handleSubmit} >Send</div>
            </div>
        </div>
    );
});

export default ChatInputPanel;